package com.cbgolf.oa.views;

import android.app.Activity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.LayoutParams;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.cbgolf.oa.R;
import com.cbgolf.oa.adapter.recycle.CommonAdapter;
import com.cbgolf.oa.adapter.recycle.ViewHolder;
import com.cbgolf.oa.base.BaseViewNew;
import com.cbgolf.oa.contract.IListStatisticsContract.IListStatisticsView;
import com.cbgolf.oa.contract.IListStatisticsContract.IListStatisticsWaiter;
import com.cbgolf.oa.entity.ListBean;
import com.cbgolf.oa.entity.StatisticsBean;
import com.cbgolf.oa.event.EventStatistics;
import com.cbgolf.oa.manager.DataManager;
import com.cbgolf.oa.manager.PopManager;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.CollectionUtil;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.DateUtil;
import com.cbgolf.oa.util.DensityUtil;
import com.cbgolf.oa.util.ScreenUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.TypeUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.util.ViewUtils;
import com.cbgolf.oa.widget.RecyclerItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import java.util.ArrayList;
import java.util.List;

/**
 * 统计列表view imp
 *
 * @author lq
 */
public class ListStatisticsViewImp extends BaseViewNew implements IListStatisticsView,
    OnRefreshLoadmoreListener {

  @BindView(R.id.topBack_ll)
  View topBack;
  @BindView(R.id.title_tv)
  TextView titleTv;
  @BindView(R.id.title_iv)
  ImageView titleIv;
  @BindView(R.id.title_ll)
  View titleView;

  @BindView(R.id.ll_filter_layout_bar)
  View filterBar;
  @BindView(R.id.ll_filter_calendar_layout)
  View calendarView;
  @BindView(R.id.tv_filter_date)
  TextView dateTv;

  @BindView(R.id.ll_filter)
  View filterView;
  @BindView(R.id.tv_filter)
  TextView filterTv;

  @BindView(R.id.refresh)
  SmartRefreshLayout refreshLayout;
  @BindView(R.id.recycleView)
  RecyclerView recyclerView;

  /**
   * worker
   */
  private IListStatisticsWaiter worker;
  /**
   * 对应不同的数据
   */
  private int mType;

  private CommonAdapter<ListBean> adapter;
  private List<ListBean> listData = new ArrayList<>();
  /**
   * 头部过滤
   */
  private List<ListBean> listTopFilter = new ArrayList<>();
  /**
   * 如打球人，全部，未到场，已到场
   */
  private List<ListBean> listFilterType = new ArrayList<>();
  private String[] playerFitler = new String[]{
      "全部", "下场", "未下场"
  };
    private String[] bussinessFitler = new String[]{
      "全部", "已结帐", "未结账"
  };
  private String[] bookFitler = new String[]{
      "全部", "到场", "未到场"
  };
  private String[] playerFitlerId = new String[]{
      "", "true", "false"
  };
    private String[] bussinessFitlerId = new String[]{
      "", "YES", "NO"
  };
  private String[] bookFitlerId = new String[]{
      "TOTAL", "COME", "NOCOME"
  };
  private StatisticsBean mData;

  public ListStatisticsViewImp(Activity act, IListStatisticsWaiter waiter, int type,
      StatisticsBean data) {
    this.worker = waiter;
    mData = data;
    mType = type;
    ButterKnife.bind(this, act);
    super.init(act);
  }

  @Override
  protected void setViews() {
    ViewUtils.setText(titleTv, worker.getActivityTitle());
    switch (mType) {
      case DataManager.STATISTICS_BUSINESS_ALL:
        ViewUtils.setVisible(filterView, false);
        ViewUtils.setText(filterTv, bussinessFitler[0]);
        initPlayerFilter(bussinessFitler, bussinessFitlerId);
        break;
      case DataManager.STATISTICS_BOOK_ALL:
        ViewUtils.setVisible(filterView, false);
        initPlayerFilter(bookFitler, bookFitlerId);
//        ViewUtils.setVisible(filterView, true);
        ViewUtils.setText(filterTv, bookFitler[0]);
        break;
      case DataManager.STATISTICS_CADDIE_ALL:
        if (null != mData) {
          listTopFilter = mData.listNameId;
        }
        ViewUtils.setVisible(filterView, false);
        break;
      case DataManager.STATISTICS_BILL_ALL:
        if (null != mData) {
          listTopFilter = mData.listNameId;
        }
        ViewUtils.setVisible(filterView, false);
        break;
      case DataManager.STATISTICS_PLAYER_ALL:
        ViewUtils.setText(filterTv, playerFitler[0]);
        ViewUtils.setVisible(filterView, true);
        initPlayerFilter(playerFitler, playerFitlerId);
        break;
      default:
        break;
    }
    ViewUtils.setVisible(calendarView, true);
    ViewUtils.setVisible(titleIv, true);
    ViewUtils.setImage(titleIv, R.mipmap.teetime_arrowdown);
    ViewUtils.setVisible(filterBar, true);
    ViewUtils.setRefreshCircleHeader(context, refreshLayout);
    ViewUtils.setText(dateTv, null != mData ? mData.mDateString : "");
    setListAdapter();
  }


  /**
   * 初始筛选数据
   */
  private void initPlayerFilter(String[] filterNames, String[] filterIds) {
    ListBean bean;
    if (!CollectionUtil.arrayIsNull(filterIds) && !CollectionUtil.arrayIsNull(filterNames)) {
      listFilterType.clear();
      for (int i = 0; i < filterNames.length; i++) {
        bean = new ListBean();
        bean.nameForShow = filterNames[i];
        bean.idForName = filterIds[i];
        listFilterType.add(bean);
      }
    }
    if (null == mData) {
      return;
    }
    listTopFilter.clear();
    if (mType == DataManager.STATISTICS_BILL_ALL) {
      if (!Util.listIsNull(mData.listNameId)) {
        listTopFilter.addAll(mData.listNameId);
      }
      return;
    }
    if (!Util.listIsNull(mData.listBarData)) {
      for (int i = 0; i < mData.listBarData.size(); i++) {
        bean = new ListBean();
        switch (mType) {
          case DataManager.STATISTICS_BUSINESS_ALL:
            bean.nameForShow = Util.isNull(mData.listBarData.get(i).x) ?
                mData.listBarData.get(i).lastX : mData.listBarData.get(i).x;
            bean.idForName = mData.listBarData.get(i).xcode;
            break;
          case DataManager.STATISTICS_BOOK_ALL:
            bean.nameForShow = Util.isNull(mData.listBarData.get(i).x) ?
                mData.listBarData.get(i).lastX : mData.listBarData.get(i).x;
            bean.idForName = TextUtil.contains(bean.nameForShow, "app") ? DataManager.ON_LINE
                : DataManager.OUT_LINE;
            break;
          case DataManager.STATISTICS_CADDIE_ALL:
            break;
          case DataManager.STATISTICS_PLAYER_ALL:
            bean.nameForShow = mData.listBarData.get(i).x;
            bean.idForName = mData.listBarData.get(i).xid;
            break;
          default:
            break;
        }
        if (Util.isNull(bean.nameForShow)) {
          continue;
        }
        listTopFilter.add(bean);
      }
    }
  }


  @Override
  protected void setListener() {
    refreshLayout.setOnRefreshLoadmoreListener(this);
    ViewUtils.setClick(topBack, v -> worker.back());
    ViewUtils.setClick(filterView, v -> showFilter());
    ViewUtils.setClick(titleView, v -> showTitleFilter());
  }


  /**
   * 公共adapter ，因为数据结构或字段不统一，所以进行了多种处理
   */
  private void setListAdapter() {
    adapter = new CommonAdapter<ListBean>(context, mType == DataManager.STATISTICS_BILL_ALL
        || mType == DataManager.STATISTICS_CADDIE_ALL ?
        R.layout.item_order : R.layout.item_rcy_list, listData) {
      @Override
      protected void convert(ViewHolder holder, ListBean data, int position) {
        if (null == data) {
          return;
        }
        if (data.isNoData && listData.size() == 1) {
          holder.setVisible(R.id.g_error_ll, true)
              .setVisible(R.id.layout, false)
              .setText(R.id.g_error_tv, data.noDataText)
              .setImageResource(R.id.g_error_logo_iv, ErrorView.getLogoRes(data.errorCode));
          ViewUtils.setLayoutParams(holder.getView(R.id.g_error_layout_ll), ScreenUtil.getWidth(),
              ScreenUtil.getHeight() - DensityUtil.dip2px(context, 48));
          return;
        }
        if (mType == DataManager.STATISTICS_BILL_ALL) {
          holder.setText(R.id.item_order_time_tv,
              DateUtil.stampToDate(data.recordDate))
              .setText(R.id.item_order_cardnum_tv, TextUtil.Text(data.consumerCar))
              .setText(R.id.item_order_userid_tv, TextUtil.Text(data.identityName))
              .setText(R.id.item_order_state_tv, TextUtil.Text(data.status))
              .setText(R.id.item_order_name_tv, TextUtil.Text(data.customerName))
              .setText(R.id.item_order_dengjiren_tv, TextUtil.Text(data.creatorName))
              .setText(R.id.tv_worker_tag, "操作人")
              .setText(R.id.item_order_paymoney_username_tv, TextUtil.Text(data.signingName))
              .setText(R.id.item_order_money_tv, "￥" + TextUtil.textNumFloat(data.signed))
              .setOnClickListener(R.id.item_order_details_tv,
                  v -> worker.showDetails(data));
          return;
        }
        if (mType == DataManager.STATISTICS_CADDIE_ALL) {
          holder.setText(R.id.tv_reg_tag, "球僮编号")
              .setText(R.id.item_order_time_tv, TextUtil.Text(data.caddieNo))
              .setText(R.id.tv_card_tag, "联系方式")
              .setText(R.id.item_order_cardnum_tv, TextUtil.Text(data.phone))
              .setText(R.id.tv_id_tag, "出场次数")
              .setText(R.id.item_order_userid_tv, TextUtil.textNumFloat(data.playTimes))
              .setText(R.id.tv_state_tag, "姓名")
              .setText(R.id.item_order_state_tv, TextUtil.Text(data.caddieName))
              .setText(R.id.tv_name_tag, "等级")
              .setText(R.id.item_order_name_tv, Util.isNull(data.levelName) ? ""
                  : TextUtil.Text(data.levelName) + "等级")
              .setText(R.id.tv_reguser_tag, "出场总时长")
              .setText(R.id.item_order_dengjiren_tv,
                  DateUtil.getHourSecond(TypeUtil.parseLong(data.playTime)))
              .setVisible(R.id.ll_money, false)
//              .setText(R.id.tv_money_tag, "操作人")
//              .setText(R.id.item_order_money_tv, TextUtil.Text(null, TextUtil.TAGNULL))
              .setVisible(R.id.tv_worker_tag, false)
              .setText(R.id.item_order_details_tv, "出场明细")
              .setOnClickListener(R.id.item_order_details_tv,
                  v -> worker.showDetails(data));
          return;
        }
        String id = "";
        String date = null;
        String cardNum = null;
        String name = null;
        String idName = null;
        String money = null;
        String workerName = null;
        String hole = null;
        String personNum = null;
        switch (mType) {
          case DataManager.STATISTICS_BOOK_ALL:
            date = data.reserveTime;
            name = data.name;
            idName = data.identify;
            personNum = data.person;
            money = data.payable;
            workerName = data.operator;
            holder.setText(R.id.tv_itemrcy_state, Util.isEquals(data.come, true) ? "已到场" : "未到场");
            holder.setVisible(R.id.tv_itemrcy_state, !Util.isNull(data.come));
            id = data.id;
            holder.setText(R.id.tv_date_tag, "预订时间");
            break;
          case DataManager.STATISTICS_BUSINESS_ALL:
            date = data.recordTime;
            cardNum = data.consumerCard;
            name = data.name;
            idName = data.identify;
            money = data.payable;
            workerName = data.operator;
            id = data.id;
            holder.setText(R.id.tv_itemrcy_playnum, TextUtil.Text(data.operator));
            holder.setText(R.id.tv_itemrcy_state, Util.isEquals(data.cashStatus , true) ? "已结账" : "未结账");
            holder.setVisible(R.id.tv_itemrcy_state, !Util.isNull(data.cashStatus));
            holder.setText(R.id.tv_playnum_tag, "登记人");
            break;
          case DataManager.STATISTICS_CADDIE_ALL:

            break;

          case DataManager.STATISTICS_PLAYER_ALL:
            date = data.recordDateTime;
            cardNum = data.consumerCard;
            name = data.name;
            idName = data.identifyName;
            money = data.amount;
            ViewUtils.setInVisible(holder.getView(R.id.ll_playnum), true);
            holder.setText(R.id.tv_itemrcy_state, Util.isEquals(data.play, true) ? "下场" : "未下场");
            holder.setVisible(R.id.tv_itemrcy_state, !Util.isNull(data.play));
            workerName = data.operator;
            id = data.customerId;
            break;
          default:
            break;
        }

        String finalId = id;

        holder.setVisible(R.id.layout, true)
            .setVisible(R.id.g_error_ll, false)
            .setText(R.id.tv_itemrcy_date,
                TypeUtil.parseLong(date) > 0 ? DateUtil.stampToDate(date) : "")
            .setText(R.id.tv_itemrcy_cardnum, TextUtil.Text(cardNum))
            .setText(R.id.tv_itemrcy_name, TextUtil.Text(name))
            .setText(R.id.tv_itemrcy_id, TextUtil.Text(idName))
            .setText(R.id.tv_itemrcy_money, "￥" + TextUtil.textNumFloat(money))
            .setVisible(R.id.ll_itemrcy_money, mType != DataManager.STATISTICS_BOOK_ALL)
            .setText(R.id.tv_itemrcy_worker_name, TextUtil.Text(workerName))
            .setText(R.id.tv_itemrcy_teetime, TextUtil.Text(data.playTime))
            .setText(R.id.tv_name, TextUtil.Text(name))
            .setText(R.id.tv_id, TextUtil.Text(idName, TextUtil.TAGNULL))
            .setText(R.id.tv_itemrcy_personnum, TextUtil.textNumInt(personNum))
            .setText(R.id.tv_itemrcy_holenum, TextUtil.Text(hole))
            .setVisible(R.id.ll_hole, !Util.isNull(hole))
            .setVisible(R.id.ll_itemrcy_teetime, mType == DataManager.STATISTICS_BOOK_ALL)
            .setVisible(R.id.ll_itemrcy_hole, mType == DataManager.STATISTICS_BOOK_ALL)
            .setVisible(R.id.ll_itemrcy_name_and_id, mType == DataManager.STATISTICS_BOOK_ALL)
            .setVisible(R.id.ll_itemrcy_cardnum_and_name,
                !(mType == DataManager.STATISTICS_BOOK_ALL))
            .setVisible(R.id.ll_itemrcy_id_and_playcount,
                !(mType == DataManager.STATISTICS_BOOK_ALL))
            .setOnClickListener(R.id.tv_itemrcy_show_details,
                v -> worker.showDetails(new ListBean
                    .Builder()
                    .setId(finalId)
                    .setOrderType(data.orderClassification)
                    .build()));
      }
    };
    LinearLayoutManager lm = new LinearLayoutManager(context);
    lm.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(lm);
    recyclerView.setHasFixedSize(true);
    recyclerView.addItemDecoration(new RecyclerItemDecoration(DensityUtil.dip2px(context, 5),
        0, 0, 0));
    recyclerView.setAdapter(adapter);

  }

  /**
   * 头顶类别筛选
   */
  private void showTitleFilter() {

    PopManager.getInstance()
        .setWidth(ScreenUtil.getWidth())
        .setHeight(LayoutParams.WRAP_CONTENT)
        .setItemlayout(R.layout.item_tv_blue)
        .setAsView(titleView)
        .setListData(listTopFilter)
        .setListWorker((id, name, position) -> {
          ViewUtils.setText(titleTv, name);
          if (null != mData) {
            mData.barQueryId = id;
            mData.payCode = id;
            mData.lineType = id;
            mData.signingId = id;
          }
          if (DataManager.STATISTICS_CADDIE_ALL == mType) {
            if (!Util.isNull(name)) {
              worker.filterCaddieData(name.replace("级", ""), mData, DataUtil.INITDATA);
            } else {
              Util.show("sorry,caddie level is error");
            }
            return;
          }
          worker.requestData(mType, mData, DataUtil.INITDATA);
        }).showList(context);


  }

  /**
   * 状态筛选
   */
  private void showFilter() {
    PopManager.getInstance()
        .setWidth(ScreenUtil.getWidth() / 4)
        .setHeight(LayoutParams.WRAP_CONTENT)
        .setItemlayout(R.layout.pop_item_tv)
        .setAsView(filterView)
        .setListData(listFilterType)
        .setListWorker((id, name, position) -> {
          ViewUtils.setText(filterTv, name);
          if (null != mData) {
            mData.isCome = id;
            mData.payIncome = id;
            mData.reserveType = id;
          }
          worker.requestData(mType, mData, DataUtil.INITDATA);
        }).showList(context);

  }

  @Override
  public void showProgress() {
    if (refreshLayout.isLoading() || refreshLayout.isRefreshing()) {
      return;
    }
    AnimaUtil.showLoading(context);
  }

  @Override
  public void stopProgress() {
    if (null != refreshLayout) {
      refreshLayout.finishRefresh();
      refreshLayout.finishLoadmore();
    }
    AnimaUtil.stopLoading();
  }

  @Override
  public void requestFail(String msg, int code) {
    listData.clear();
    listData.add(new ListBean.Builder()
        .setError(msg, code)
        .setIsNoData(true)
        .build());
    adapter.notifyDataSetChanged();
  }

  @Override
  public void requestOver(EventStatistics event) {
    if (null == event) {
      return;
    }
    stopProgress();
    switch (event.msgTarget) {
      case DataManager.STATISTICS_BUSINESS_LIST:
      case DataManager.STATISTICS_PLAYER_LIST:
      case DataManager.STATISTICS_BOOK_LIST:
      case DataManager.STATISTICS_CADDIE_LIST:
      case DataManager.STATISTICS_BILL_LIST:
        checkPlayerDataAndShow(event);
        break;
      default:
        break;
    }

  }

  private void checkPlayerDataAndShow(EventStatistics event) {
    switch (event.requestEvent) {
      case DataUtil.REFRESH:
        if (Util.listIsNull(event.listStatisticsData)) {
          return;
        }
        showData(event.listStatisticsData);
        break;
      case DataUtil.LOADMORE:
        if (Util.listIsNull(event.listStatisticsData)) {
          return;
        }
        listData.addAll(event.listStatisticsData);
        adapter.notifyDataSetChanged();
        break;
      default:
        if (Util.listIsNull(event.listStatisticsData)) {
          requestFail(event.errorMsg, event.errorCode);
          return;
        }
        showData(event.listStatisticsData);
        break;
    }
  }

  private void showData(List<ListBean> list) {
    listData.clear();
    listData.addAll(list);
    adapter.notifyDataSetChanged();
  }

  @Override
  public void onLoadmore(RefreshLayout refreshlayout) {
    worker.loadMoer();
  }

  @Override
  public void onRefresh(RefreshLayout refreshlayout) {
    worker.refresh();
  }
}
